package com.jake.sap.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Queue;

import static com.jake.common.constant.SizeConstants.SAP_MAX_CONNECTION_SIZE;
import static com.jake.common.constant.SizeConstants.SAP_THRESHOLD_SIZE;

@Aspect
@Component
@Slf4j
public class QueriesCountAspect {

    @Autowired
    private ConnectionReleaseService connectionReleaseService;
    
    @Autowired
    @Qualifier(value = "sapConcurrentQueue")
    private Queue<LocalDateTime> sapConcurrentQueue;

    @Pointcut("execution(public java.util.Map<String, Object> com.jake.sap.service.AttendanceService.*(..))")
    public void countQueries(){}

    @Before(value = "countQueries()")
    public void add() {
        sapConcurrentQueue.offer(LocalDateTime.now());
        log.warn("add: the concurrent count queries to sap is {}", sapConcurrentQueue.size());
    }

    @AfterReturning(pointcut = "countQueries()")
    public void subtract() {
        int size = sapConcurrentQueue.size();
        if (size > SAP_THRESHOLD_SIZE) {
            connectionReleaseService.releaseLatest();
        }
        if (size >= SAP_MAX_CONNECTION_SIZE) {
            log.error("subtract: the number of connections is {}, " +
                    "which overpasses the maximum", size);
        }
    }

}
